package cn.iocoder.yudao.module.measure.mq.rabbit;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.listener.MessageListenerContainer;
import org.springframework.amqp.rabbit.listener.RabbitListenerEndpointRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;


@Component
@Slf4j
public class RabbitApplicationRunner implements CommandLineRunner {



    @Autowired
    private RabbitListenerEndpointRegistry registry;


    /**
     * 此方法初始化设备协议缓存
     * 启动接收设备上传消息的mq消费者
     * @param args incoming main method arguments
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        try{
//            log.info("初始化设备协议缓存");
            //  清除缓存的设备协议信息
//        cacheOps.flushDb();
            // 启动mq接收
            String[] listeners = new String[] { "readDeviceUploadMessage" };
            for (String listenerId: listeners) {
                MessageListenerContainer container = registry.getListenerContainer(listenerId);
                if (container == null) {
                    log.info(listenerId + " is null.");
                } else {
                    if (container.isRunning()) {
                        log.info(listenerId +" is running.");
                    } else {
                        container.start();
                        log.info(listenerId + " started.");
                    }
                }
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            log.error("MQ启动时出错："+e.getMessage());
        }

    }
}
